﻿using System.Diagnostics;
using System.Windows;
using Game.Command;
using Game.Common;
using Game.Controller;
using Game.Objects;
using Game.Toolkit;

namespace SL
{
    public partial class BuildUnitWindow
    {
        readonly SchedulerCommand _Command;
        readonly CommandQueueExtension _Extension;
        readonly GameController _GameController;
        readonly GameBuilding _GameBuilding;

        public BuildUnitWindow(
            GameBuilding building,
            SchedulerCommand command,
            CommandQueueExtension extension,
            GameController gameController)
        {
            _Command = command;
            _Extension = extension;
            _GameBuilding = building;
            _GameController = gameController;
            InitializeComponent();
            Title = "Select a Vehicle";

            PopulateListbox();
            listBox1.SelectionChanged += (sender, args) => EnableButton();
            EnableButton();
        }

        void EnableButton()
        {
            if (listBox1.SelectedItems.Count > 0)
            {
                var item = listBox1.SelectedItem as VehicleListboxItem;
                if (item != null && item.IsEnabled)
                {
                    OKButton.IsEnabled = true;
                }
                else
                {
                    OKButton.IsEnabled = false;
                }
            }
            else
            {
                OKButton.IsEnabled = false;
            }
        }

        void PopulateListbox()
        {
            var vehicles = StandardToolkit.Vehicles;
            foreach (var v in vehicles)
            {
                var panel = new VehicleListboxItem(v, _GameBuilding);
                listBox1.Items.Add(panel);
            }
        }

        void OKButton_Click(object sender, RoutedEventArgs e)
        {
            var turn = GameTurn.Create();

            var panel = listBox1.SelectedItem as VehicleListboxItem;
            Debug.Assert(panel != null, "panel != null");

            var cmd = _Command.CreateScheduledCommand(panel.VehicleType);
            _Extension.ScheduledCommandQueue.Add(
                _GameController.CommandExecutor, cmd, turn);

            DialogResult = true;
        }

        void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
        }


    }
}

